import $ from '$';
import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Spin, Form, Modal, message } from 'antd';
import { Synergy } from '../components/Portal/Portal';
import {
  WeaTop,
  WeaTab,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaSearchGroup,
  WeaDialog,
  WeaInput,
  WeaDropMenu,
  WeaIntro,
  WeaFormItem,
  WeaError,
  WeaLocaleProvider,
  WeaBrowser,
} from 'ecCom';
import { WeaTableNew, WeaSwitch } from 'comsMobx';
// import { WeaTable } from '../../coms/wea-table-new';
import * as searchApi from '../apis/search';
import * as Util from '../util';
import DocLog from './Tables/DocLog';
import DocShare from './Tables/DocShare';
import { cloneDeep } from 'lodash';

const { WeaTable } = WeaTableNew;
const confirm = Modal.confirm;
const { tryCatch } = WeaTools;
const WeaIntroStep = WeaIntro.Step;
const store = [
  'docMyDocStore',
  'docLatestDocStore',
  'docAllDocStore',
  'routing',
  'docDocLogStore',
  'docDocShareStore',
];
const getLabel = WeaLocaleProvider.getLabel;
@tryCatch(
  React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@14cq8e`} msg={props.error || getLabel(385218, '对不起，该页面异常，请联系管理员！')} />,
  { error: '' },
)
@inject('docSearchStore', ...store)
@observer
class Search extends React.Component {
  constructor(props) {
    super(props);
    this.isMouted = false;
    this.onOperatesClick = this.onOperatesClick.bind(this);
    this.onTabEdit = this.onTabEdit.bind(this);
    this.state = {
      menuidforportal: '',
      searchType: ["base", "advanced"],
      dropMenuProps: {
        collectParams: {
          favname: getLabel(132039, '查阅文档'),
          favouritetype: 2,
          objid: 0,
          importantlevel: 1,
          link: 'wui/index.html#/main/document/search',
        },
      },
    };
  }
  componentDidMount() {
    this.isMouted = true;
    const { location, docSearchStore } = this.props;
    const { query = {}, state = {} } = location;
    const { prePath = '', prePathName = '' } = state;
    let viewcondition;
    const elementmore = query.jsonstr ? { elementmore: query.jsonstr } : {};
    const secid = query.secid ? query.secid : '';
    const getMost = query.getMost ? query.getMost : '';
    const menuidforportal = query.menuidforportal ? query.menuidforportal : '';
    delete query.jsonstr;
    delete query.fromwhere;
    this.setState({ menuidforportal });
    this.props[store[2]].initTreeNumData();
    docSearchStore.installLeftTree();
    docSearchStore.getDefaultTree({ ...query }).then(() => {
      let stateParam = {};
      if (viewcondition) stateParam.viewcondition = viewcondition;
      if (getMost) stateParam.getMost = getMost;
      if (secid) stateParam.secid = secid;
      if (prePath && prePathName) {
        stateParam.prePath = prePath;
        stateParam.prePathName = prePathName;
      }
      if (docSearchStore.portalParams.fromPortal == '1') {
        viewcondition = Number(docSearchStore.portalParams.protalViewcondition);
      } else {
        viewcondition = 2;
      }
      docSearchStore.setState({ viewcondition });
      // docSearchStore.setState({viewcondition});
      // viewcondition && docSearchStore.setState({ viewcondition });
      //  getMost && docSearchStore.setState({getMost});
      //  secid && docSearchStore.setState({secid});
      //  prePath && prePathName && docSearchStore.setState({ prePath, prePathName });

      stateParam.categoryid = '';
      stateParam.canCreate = false;
      docSearchStore.getTabInfo({ ...query });
      docSearchStore.createUrl();
      // docSearchStore.categoryid = '';
      // docSearchStore.canCreate = false;
      this.props[store[viewcondition]]
        .doSearch('Search', { viewcondition, ...query, ...elementmore })
        // .getTreeDatas('Search', { viewcondition, ...query, isFav: docSearchStore.defaultTreeNode })
        .getRightMenu('Search', { viewcondition, ...query })
        .getConditionInfo('Search', { viewcondition, ...query });
      // .getTreeNums('Search', { viewcondition, ...query, isFav: docSearchStore.defaultTreeNode });
      // 如果是默认全部文档，则取消收藏不能变动初定设置
      const _this = this;
      if (docSearchStore.defaultTreeNode == 0) {
        //   docSearchStore.isNotDefaultFav = true;
        stateParam.isNotDefaultFav = true;
      }
      docSearchStore.setState(stateParam);

      if (docSearchStore.leftTree.showLeft && !docSearchStore.leftTree.hasLoad) {
        this.props[store[viewcondition]]
          .getTreeDatas('Search', { viewcondition, ...query, isFav: docSearchStore.defaultTreeNode });
        // .getTreeNums('Search', { viewcondition, ...query, isFav: docSearchStore.defaultTreeNode });
      }

      // 处理jquery版本升级 live方法不存在问题
      $('body').on('click', '.wea-doc-search .wea-new-table td .wea-url>a', function () {
        if ($(this)[0].href && $(this)[0].href.indexOf('openFullWindowForXtable') > 0
          && $(this).next('img').length > 0) {
          $(this).next('img').css('display', 'none');
          const _viewcondition = docSearchStore.viewcondition;
          if (_this.isMouted && _viewcondition == 1) {
            const storeNow = _this.props[store[_viewcondition]];
            storeNow.doSearch('Search', {
              viewcondition: _viewcondition,
              getMost,
              secid,
              ...storeNow.form.getFormParams(),
              current: storeNow.comsWeaTableStore.current,
            });
          }
        }
      });
      // $('.wea-doc-search .wea-new-table td .wea-url>a').live('click', function () {
      //   if ($(this)[0].href && $(this)[0].href.indexOf('openFullWindowForXtable') > 0
      //     && $(this).next('img').length > 0) {
      //     $(this).next('img').css('display', 'none');
      //     const _viewcondition = docSearchStore.viewcondition;
      //     if (_this.isMouted && _viewcondition == 1) {
      //       const storeNow = _this.props[store[_viewcondition]];
      //       storeNow.doSearch('Search', {
      //         viewcondition: _viewcondition,
      //         getMost,secid,
      //         ...storeNow.form.getFormParams(),
      //         current: storeNow.comsWeaTableStore.current,
      //       });
      //     }
      //   }
      // });
    });
  }
  componentWillMount() {
    const { docSearchStore } = this.props;
    docSearchStore.setState({ categoryid: '' });
  }
  componentWillUnmount() {
    const _this = this;
    const { docSearchStore } = this.props;
    const { defaultTreeNode } = docSearchStore;
    const _viewcondition = docSearchStore.viewcondition;
    const storeNow = _this.props[store[_viewcondition]];
    docSearchStore.setState({
      viewcondition: 0,
      showSearchAd: false,
      showThumbnails: false,
      checkedKeys: [],
      treeDropMenuKey: defaultTreeNode,
      dcategoryid: '',
    });
    this.isMouted = false;
    if (storeNow && storeNow.comsWeaTableStore) {
      storeNow.comsWeaTableStore.setSelectedRowKeys([]);
      storeNow.comsWeaTableStore.sortParams = [];
    }
  }
  componentWillReceiveProps(nextProps) {
    this.isMouted = true;
    const { location, docSearchStore } = nextProps;
    const { query = {}, state = {} } = location;
    const { prePath = '', prePathName = '' } = state;
    let viewcondition;
    const elementmore = query.jsonstr ? { elementmore: query.jsonstr } : {};
    const secid = query.secid ? query.secid : '';
    const getMost = query.getMost ? query.getMost : '';
    const menuidforportal = query.menuidforportal ? query.menuidforportal : '';
    delete query.jsonstr;
    delete query.fromwhere;
    this.setState({ menuidforportal });
    this.props[store[2]].initTreeNumData();
    // alert(secid);
    if (location.key != this.props.location.key) {
      docSearchStore.installLeftTree();
      docSearchStore.getDefaultTree({ ...query }).then(() => {
        let stateParam = {};
        if (viewcondition) stateParam.viewcondition = viewcondition;
        if (getMost) stateParam.getMost = getMost;
        if (secid) stateParam.secid = secid;
        if (prePath && prePathName) {
          stateParam.prePath = prePath;
          stateParam.prePathName = prePathName;
        }
        stateParam.categoryid = '';
        stateParam.canCreate = false;
        if (docSearchStore.portalParams.fromPortal == '1') {
          viewcondition = Number(docSearchStore.portalParams.protalViewcondition);
        } else {
          viewcondition = 2;
        }
        docSearchStore.setState({ viewcondition });
        docSearchStore.getTabInfo({ ...query });
        docSearchStore.createUrl();
        // docSearchStore.categoryid = '';
        // docSearchStore.canCreate = false;
        nextProps[store[viewcondition]]
          .doSearch('Search', { viewcondition, ...query, ...elementmore })
          // .getTreeDatas('Search', { viewcondition, ...query, isFav: docSearchStore.defaultTreeNode })
          .getRightMenu('Search', { viewcondition, ...query })
          .getConditionInfo('Search', { viewcondition, ...query });
        // .getTreeNums('Search', { viewcondition, ...query, isFav: docSearchStore.defaultTreeNode });
        docSearchStore.setState(stateParam);

        if (docSearchStore.leftTree.showLeft && !docSearchStore.leftTree.hasLoad) {
          nextProps[store[viewcondition]]
            .getTreeDatas('Search', { viewcondition, ...query, isFav: docSearchStore.defaultTreeNode });
          // .getTreeNums('Search', { viewcondition, ...query, isFav: docSearchStore.defaultTreeNode });
        }

        const _this = this;
        // 处理jquery版本升级 live方法不存在问题
        $('body').on('click', '.wea-doc-search .wea-new-table td .wea-url>a', function () {
          if ($(this)[0].href && $(this)[0].href.indexOf('openFullWindowForXtable') > 0
            && $(this).next('img').length > 0) {
            $(this).next('img').css('display', 'none');
            const _viewcondition = docSearchStore.viewcondition;
            if (_this.isMouted && _viewcondition == 1) {
              const storeNow = nextProps[store[_viewcondition]];
              storeNow.doSearch('Search', {
                viewcondition: _viewcondition,
                getMost,
                secid,
                ...storeNow.form.getFormParams(),
                current: storeNow.comsWeaTableStore.current,
              });
            }
          }
        });
        // $('.wea-doc-search .wea-new-table td .wea-url>a').live('click', function () {
        //   if ($(this)[0].href && $(this)[0].href.indexOf('openFullWindowForXtable') > 0
        //     && $(this).next('img').length > 0) {
        //     $(this).next('img').css('display', 'none');
        //     const _viewcondition = docSearchStore.viewcondition;
        //     if (_this.isMouted && _viewcondition == 1) {
        //       const storeNow = nextProps[store[_viewcondition]];
        //       storeNow.doSearch('Search', {
        //         viewcondition: _viewcondition,
        //         getMost,secid,
        //         ...storeNow.form.getFormParams(),
        //         current: storeNow.comsWeaTableStore.current,
        //       });
        //     }
        //   }
        // });
      });
    }
  }
  doDocDelete=(params)=> {
    searchApi.doDeleteWarm().then((data) => {
      confirm({
        content: (
          <span>
            {data.title}
            {
              data.subTitle ? <span style={{ color: 'red' }}>({data.subTitle})</span> : null
            }
          </span>
        ),
        onOk: () => {
          searchApi.doDelete(params).then((_data) => {
            if (_data.status === 1) {
              const { docSearchStore } = this.props;
              const { viewcondition, getMost, secid } = docSearchStore;
              const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
              storeNow.doSearch('Search', {
                viewcondition,
                getMost,
                secid,
                ...storeNow.form.getFormParams(),
                current: storeNow.comsWeaTableStore.current,
              });
              message.success(_data.msg);
            } else {
              message.error(_data.msg);
            }
          });
        },
        onCancel() { },
      });
    });
  }
  onOperatesClick=(record, index, operate)=> {
    const { docSearchStore, docDocLogStore, docDocShareStore } = this.props;
    const funName = operate.href.replace(/(javascript\:)|(\(\))/g, () => '');
    if (funName === 'doEdit') {
      Util.openWindow(
        `/spa/document/index.jsp?id=${record.id}&isEdit=1&router=1#/main/document/edit`,
      );
    } else if (funName === 'doMuliDelete') {
      this.doDocDelete({ docid: record.id });
    } else if (funName === 'doDocShare') {
      docSearchStore.setState({ showDocShare: true, shareDocId: record.id });
      docDocShareStore.doSearch('DocShare', { docid: record.id })
        .canShareAddEdit({ docid: record.id });
    } else if (funName === 'doDocViewLog') {
      docSearchStore.setState({ showDocLog: true, logDocId: record.id });
      docDocLogStore.getTabInfo({ docid: record.id })
        .getRightMenu('DocLog')
        .getConditionInfo('DocLog')
        .doSearch('DocLog', { viewcondition: 0, docid: record.id });
    }
  }
  onTabEdit=(targetKey, action)=> {
    const { location } = this.props;
    const { query = {} } = location;
    if (action === 'remove') {
      Modal.confirm({
        title: getLabel(385139, '确定要删除这个搜索模板吗？'),
        onOk: () => {
          const { docSearchStore } = this.props;
          const { tabInfo } = docSearchStore;
          const _viewcondition = docSearchStore.viewcondition;
          const storeNow = this.props[store[_viewcondition > 2 ? 2 : _viewcondition]];
          const { form } = storeNow;
          let _groupid = '';
          form.reset();
          tabInfo.forEach((tab) => {
            if (tab.viewcondition === Number(targetKey)) _groupid = tab.groupid;
          });
          docSearchStore.delTabPane({ groupid: _groupid });
          const viewcondition = _viewcondition === Number(targetKey)
            ? _viewcondition - 1 : _viewcondition;
          const index = viewcondition > 2 ? 2 : viewcondition;
          let groupid = '';
          tabInfo.forEach((tab) => {
            if (tab.viewcondition === Number(viewcondition)) groupid = tab.groupid;
          });
          storeNow.doSearch('Search', { ...query, viewcondition, groupid })
            .getRightMenu('Search', { viewcondition: index, groupid })
            .getConditionInfo('Search', { viewcondition, groupid });
          // this.props[store[index]].treeDatas.length === 0 &&
          storeNow.getTreeDatas('Search', { ...query, viewcondition: index, groupid, isFav: docSearchStore.defaultTreeNode })
            .getTreeNums('Search', { ...query, viewcondition: index, groupid, isFav: docSearchStore.defaultTreeNode });
          docSearchStore.setState({ viewcondition });
        },
      });
    }
  }
  onVisibleChange=(bool, index)=> {
    const { docSearchStore } = this.props;
    const { viewcondition } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { conditioninfo, setConditionInfo } = storeNow;
    let condition = cloneDeep(toJS(conditioninfo));
    condition[index].defaultshow = bool;
    setConditionInfo(condition);
  }
  onSearch=()=> {
    const { docSearchStore } = this.props;
    const { menuidforportal } = this.state;
    const { viewcondition, getMost, secid, tabInfo } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { form } = storeNow;
    storeNow.doSearch('Search', { viewcondition, getMost, secid, ...form.getFormParams(), menuidforportal });
    docSearchStore.setState({ showSearchAd: false, checkedKeys: [] });
  }
  getSearchs=()=> {
    const { docSearchStore } = this.props;
    const { viewcondition } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { conditioninfo, form, formParams } = storeNow;
    const { isFormInit } = form;
    const group = [];
    {/* const  formParams= form.getFormParams(); */ }
    isFormInit && toJS(conditioninfo).forEach((c, index) => {
      let items = [];
      c.items.forEach((field) => {
        if (field.isQuickSearch) {
          this.quickSearchPara = field.domkey[0];
        }
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@k4lx5w@${field.domkey[0]}`}
              label={`${field.label}`}
              labelCol={{ span: field.labelcol }}
              wrapperCol={{ span: field.fieldcol }}
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@nmjgqp@${field.domkey[0]}`} fieldConfig={field} form={form} formParams={formParams} onEnterSearch={this.onSearch} />
            </WeaFormItem>
          ),
          colSpan: 1,
        });
      });
      group.push(
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@b0uwta@${c.title}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} onVisibleChange={this.onVisibleChange} />,
      );
    });
    return group;
  }
  getTabButtonsAd=()=> {
    const { docSearchStore } = this.props;
    const { menuidforportal } = this.state;
    const { viewcondition, getMost, secid, tabInfo } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { form } = storeNow;
    const onSearchClick=() => {
        storeNow.doSearch('Search', { viewcondition, getMost, secid, ...form.getFormParams(), menuidforportal });
        docSearchStore.setState({ showSearchAd: false, checkedKeys: [] });
      }
    const onSaveClick=() => {
        tabInfo.map((tab) => {
          if (tab.viewcondition === viewcondition) {
            docSearchStore.addTabPane({ conditionMouldId: tab.groupid, ...form.getFormParams() });
            docSearchStore.setState({
              showConditonSave: false,
              showSearchAd: false,
              conditionMouldName: '',
            });
          }
        });
      }
    const onSaveToClick=() => {
        docSearchStore.setState({ showConditonSave: true });
      }

    const onResetClick=() => form.reset()
    
    const onCancel =() => docSearchStore.setState({ showSearchAd: false })

    const btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qabz8v@search`} type="primary"
      onClick={onSearchClick}
    >{getLabel(197, '搜索')}</Button>];
    viewcondition > 2 && btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@d894o6@save`} type="primary"
      onClick={onSaveClick}
    >{getLabel(86, '保存')}</Button>);
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7nuspp@saveAs`} type="primary"
      onClick={onSaveToClick}
    >{getLabel(350, '另存为')}</Button>);
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@brh0w7@reset`} type="ghost" onClick={onResetClick}>{getLabel(2022, '重置')}</Button>);
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ocs4q8@cancel`} type="ghost"
      onClick={onCancel}
    >{getLabel(31129, '取消')}</Button>);
    return btns;
  }

  getRightMenu=(isTop = false)=> {
    const { routing, docSearchStore } = this.props;
    const { menuidforportal } = this.state;
    const { viewcondition, getMost, secid, categoryid, showThumbnails, checkedKeys, canCreate } = docSearchStore;
    const { linkRout, linkUrl, param, domKey, openNewWindow } = docSearchStore;

    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { rightMenu, comsWeaTableStore, form, loading } = storeNow;
    const { selectedRowKeys } = comsWeaTableStore;
    const loadingNow = loading || comsWeaTableStore.loading;
    const btnArr = [];
    rightMenu.forEach((m) => {
      let disabled = showThumbnails ? checkedKeys.length === 0 : selectedRowKeys.length === 0;
      let onClick = () => { };
      let content = m.menuName;
      if (m.type === 'BTN_SEARCH') { // 搜索
        disabled = false;
        onClick = () => {
          storeNow.doSearch('Search', { viewcondition, getMost, secid, ...form.getFormParams(), menuidforportal });
          docSearchStore.setState({ checkedKeys: [] });
        };
      } else if (m.type === 'BTN_BACTH_DOWNLOAD_FILE') { // 批量下载
        onClick = () => { };
      } else if (m.type === 'BTN_DELETE') {
        onClick = () => {
          this.doDocDelete({ docid: `${selectedRowKeys}` });
        };
      } else if (m.type === 'BTN_CREATE_DOC') { // 新建
        disabled = false;
        onClick = () => {
          if (canCreate === true) {
            // 有文档创建权限 直接新建
            const url = `${linkUrl}?${domKey}=${
              categoryid}${param}${linkRout}`;
            if (openNewWindow === '1') {
              window.open(url);
            } else {
              window.location.href = url;
            }
          } else {
            // 没有选择目录 弹出新建的目录浏览按钮
            if (categoryid === '') {
              // ref={c => this._container = c} 直接打开浏览按钮
              this.refs.createDoc.openModal();
            } else {
              // 没有创建权限
              Modal.confirm({
                title: getLabel(131329, '信息确认'),
                content: getLabel(390488, ' 所选目录没有权限新建,请重新选择!'),
                onOk: () => {
                  this.refs.createDoc.openModal();
                },
              });
            }
          }
        };
      } else if (m.type === 'BTN_MINIATURE_DISPLAY') { // 缩略图显示
        disabled = false;
        if (showThumbnails) content = getLabel(15360, '列表显示');
        onClick = () => {
          docSearchStore.setState({ showThumbnails: !showThumbnails, checkedKeys: [] });
        };
      } else if (m.type === 'BTN_SUBSCRIBE') { // 订阅
        disabled = false;
        onClick = () => {
          routing.push('/main/document/subscribe');
        };
      } else if (m.type === 'BTN_IMPORT_SELECT_TO_DUMMY') { // 导入选中到虚拟
        onClick = () => {
          docSearchStore.chooseDummy().setState({ showImportDummy: true, importType: 'select' });
        };
      } else if (m.type === 'BTN_IMPORT_ALL_TO_DUMMY') { // 导入全部到虚拟
        disabled = false;
        onClick = () => {
          docSearchStore.chooseDummy().setState({ showImportDummy: true, importType: 'all' });
        };
      } else if (m.type === 'BTN_SIGN_READED') { // 已读
        onClick = () => {
          docSearchStore.markReaded({ docids: `${selectedRowKeys}` }, () => {
            storeNow.doSearch('Search', { viewcondition, getMost, secid, ...form.getFormParams() });
          });
        };
      } else if (m.type === 'BTN_COLUMN') {
        disabled = false;
        onClick = () => {
          comsWeaTableStore.setColSetVisible(true);
          comsWeaTableStore.tableColSet(true);
        };
      } else {
        disabled = false;
      }
      disabled = loadingNow || disabled;
      if (isTop) {
        m.isTop === '1' && btnArr.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gye5us@${m.type}`} type="primary"
            disabled={disabled}
            onClick={onClick}
          >
            {content}
          </Button>,
        );
        btnArr.push(
          <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@wqe5ge@${m.type}`} type="doccategory"
            title={getLabel(385405, '文档目录')}
            isSingle={true}
            ref="createDoc"
            customized
            icon="icon-coms-doc"
            iconBgcolor="#f14a2d"
            dataParams={{ iscreate: 1 }}
            quickSearchName={"categoryname"}
            onChange={docSearchStore.createDoc}
          />,
        );
      } else {
        btnArr.push({
          key: m.type,
          icon: <i className={m.menuIcon} />,
          content,
          disabled,
          onClick,
        });
      }
    });

    return btnArr;
  }
  getTree=()=> {
    const { docSearchStore, location } = this.props;
    const { query = {}, state = {} } = location;
    const { viewcondition, getMost, secid, treeDropMenuKey, canCreate } = docSearchStore;
    const { defaultTreeNode, isNotDefaultFav } = docSearchStore;
    const { selectedTreeKeys } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { treeDatas, treeTypes, treeCounts, form, treeLoading, comsWeaTableStore } = storeNow;
    let treeDropMenu = [
      {
        companyid: '1',
        name: getLabel(18030, '我的收藏'),
      },
      {
        companyid: '0',
        name: getLabel(385079, '全部目录'),
      },
    ];

    return (
      <div className="wea-doc-search-left-tree" style={{ height: '100%' }}>
        <WeaIntroStep ecId={`${this && this.props && this.props.ecId || ''}_WeaIntroStep@qpo4nm`}
          step="1"
          id="document_step1"
          intro={getLabel(385089, '还没有收藏目录，点击这里可以打开全部目录')}
        >
          <WeaDropMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaDropMenu@rfi8vl`}
            value={treeDropMenuKey}
            dropMenu={treeDropMenu}
            onSelect={this.dropMenuSelect}
          />
        </WeaIntroStep>
        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@n4mv2e`} spinning={treeLoading}>
          <WeaIntroStep ecId={`${this && this.props && this.props.ecId || ''}_WeaIntroStep@5wdgod`}
            step="2"
            id="document_step2"
            intro={getLabel(385088, '鼠标移动到条目上，点击收藏 ☆ 就能添加到我的收藏列表了')}
            style={{ height: '100%' }}
          >
            <WeaLeftTree ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@x45ja5`}
              ref="leftTree"
              showCollect={true}
              asyncLoad={true}
              onExpand={this.treeExpand}
              // asyncTree={true}
              // onlyShowFav={treeDropMenuKey === defaultTreeNode}
              onlyShowFav={!isNotDefaultFav}
              selectedKeys={selectedTreeKeys}
              defaultExpandLevel={1}
              datas={toJS(treeDatas)}
              counts={treeCounts}
              countsType={toJS(treeTypes)}
              onSearchLabelClick={this.treeSearchLabelClick}
              onCollect={this.onCollect}
              onSelect={this.onTreeSelect}
            />
          </WeaIntroStep>
        </Spin>
      </div>
    );
  }

  treeExpand = (val) => {
    const { viewcondition } = this.props.docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    storeNow.getTreeNums('Search', { secid: (val.length > 0 ? val[val.length - 1].substring(4) : ''), selectChild: '1', viewcondition })
  }

  dropMenuSelect = (v) => {
    const { docSearchStore, location } = this.props;
    const { query = {}, state = {} } = location;
    const { viewcondition, secid } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    // 当是默认收藏，则按原有路线
    if (v.key === '1') {
      docSearchStore.isNotDefaultFav = false;
    } else {
      docSearchStore.isNotDefaultFav = true;
      // 非默认收藏，如修改后的默认值和key一致，则变动
    }
    storeNow.initTreeNumData();
    docSearchStore.setState({ treeDropMenuKey: v.key });
    storeNow.getTreeDatas('Search', { ...query, viewcondition, secid, isFav: v.key })
      .getTreeNums('Search', { ...query, viewcondition, secid, isFav: v.key });
    this.refs.leftTree && this.refs.leftTree.setState({ searchValue: '' });
  }

  treeSearchLabelClick = () => {
    const { docSearchStore } = this.props;
    const { viewcondition, getMost, secid } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { form } = storeNow;
    storeNow.doSearch('Search', { viewcondition, getMost, secid });
    form.reset();
    docSearchStore.setState({ checkedKeys: [] });
  }

  onCollect = (data) => {
    return WeaTools.callApi('/api/doc/category/collute', 'GET', {
      operate: data.fav ? 'undo' : 'do',
      secid: data.key,
    })
  }

  onTreeSelect = (key, topTabCount, treeNode) => {
    const { docSearchStore } = this.props;
    const { viewcondition, getMost, secid } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { comsWeaTableStore } = storeNow;

    let value = topTabCount ? topTabCount.keyid : '';
    let valueSpan = '';
    const otherParams = {};
    if (treeNode.node) {
      value = treeNode.node.props.data.key;
      valueSpan = treeNode.node.props.data.name;
    } else {
      // 小数字 呵呵哒
      if (treeNode.name === 'newNum') {
        otherParams.isNew = 'yes';
      }
      treeDatas.forEach((d) => {
        if (d.domid === key) valueSpan = d.name;
      });
    }
    let params = {
      seccategory: {
        value,
        valueSpan,
        valueObj: [
          {
            id: value,
            name: valueSpan,
          },
        ],
      },
    };

    storeNow.getConditionInfo('Search', { viewcondition, ...params },
      () => storeNow.doSearch('Search', { viewcondition, getMost, secid, ...otherParams, seccategory: treeNode.node.props.data.key }));
    docSearchStore.setState({ selectedTreeKeys: [key], checkedKeys: [] });
    if (treeNode.node.props.data.key != '') {
      docSearchStore.getAccount({ categoryid: treeNode.node.props.data.key });
      docSearchStore.setState({ categoryid: treeNode.node.props.data.key });
    }
    comsWeaTableStore.setSelectedRowKeys([]);
  }

  getConditonSave=()=> {
    const { docSearchStore } = this.props;
    const { viewcondition, showConditonSave, conditionMouldName } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { form } = storeNow;
    const onSvaeClick=() => {
                if (!conditionMouldName) {
                  this.refs.weaError.showError();
                } else {
                  docSearchStore.addTabPane({ conditionMouldName, ...form.getFormParams() });
                  docSearchStore.setState({
                    showConditonSave: false,
                    showSearchAd: false,
                    conditionMouldName: '',
                  });
                }
              }
    const onCancel = () => docSearchStore.setState({ showConditonSave: false });
    const dialogBtns = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ih42g4@$dialogSave`} type="primary"
              onClick={onSvaeClick}
            >{getLabel(30986, '保存')}</Button>),
          ]
    const moreBtn={
          datas: [{
            key: '1',
            disabled: false,
            icon: '',
            content: getLabel(30986, '保存'),
            onClick: (key) => {
              if (!conditionMouldName) {
                this.refs.weaError.showError();
              } else {
                docSearchStore.addTabPane({ conditionMouldName, ...form.getFormParams() });
                docSearchStore.setState({
                  showConditonSave: false,
                  showSearchAd: false,
                  conditionMouldName: '',
                });
              }
            },
          }],
          collectParams: {
            favname: getLabel(33144, '模板'),
            favouritetype: 2,
            objid: 0,
            importantlevel: 1,
          },
        }
    const onChange = (v) => docSearchStore.setState({ conditionMouldName: v })
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@42k8wr`}
        className="wea-doc-condition-save-modal"
        title={getLabel(350, '另存为')}
        style={{ width: 520 }}
        icon="icon-coms-doc"
        iconBgcolor="#df583a"
        maskClosable={false}
        visible={showConditonSave}
        onCancel={onCancel}
        buttons={dialogBtns}
        moreBtn={moreBtn}
      >
        <div style={{ 'padding-bottom': '50px', 'padding-top': '30px' }}>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@e6gqk4`}
            label={getLabel('385087', '搜索模板名称')}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
          >
            <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@pg3s2r`} error={getLabel(127697, '模板名称不能为空！')} ref="weaError">
              <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@o0dwc7`} placeholder={getLabel(84557, '自定义查询条件')}
                value={conditionMouldName}
                style={{ width: 300 }}
                viewAttr="3"
                onChange={onChange}
              />
            </WeaError>
          </WeaFormItem>
        </div>
      </WeaDialog>
    );
  }
  getDocShare=()=> {
    const { docSearchStore, docDocShareStore } = this.props;
    const { showDocShare, shareDocId } = docSearchStore;
    const onCancel=() => docSearchStore.setState({ showDocShare: false })
    const style=()=>{return { width: 780, height: 524 }}
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@27l9ys`}
        className="wea-doc-share-modal"
        title={getLabel(1985, '文档共享')}
        style={style()}
        maskClosable={false}
        icon="icon-coms-doc"
        iconBgcolor="#df583a"
        visible={showDocShare}
        onCancel={onCancel}

      >
        <DocShare ecId={`${this && this.props && this.props.ecId || ''}_DocShare@3rbvgy`} docid={shareDocId} />
      </WeaDialog>
    );
  }
  getDocLog=()=> {
    const { docSearchStore, docDocLogStore } = this.props;
    const { showDocLog, logDocId } = docSearchStore;
    const onCancel=() => {
          docSearchStore.setState({ showDocLog: false });
          docDocLogStore.setState({ viewcondition: 0, showSearchAd: false });
        }
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@86rckm`}
        className="wea-doc-log-modal"
        title={getLabel(21990, '文档日志')}
        style={{ width: 720, height: 'auto' }}
        maskClosable={false}
        icon="icon-coms-doc"
        iconBgcolor="#df583a"
        visible={showDocLog}
        onCancel={onCancel}

      >
        <DocLog ecId={`${this && this.props && this.props.ecId || ''}_DocLog@qsce33`} docid={logDocId} />
      </WeaDialog>
    );
  }
  getImportDummy=()=> {
    const { docSearchStore } = this.props;
    const { viewcondition, showImportDummy, importType, importLoading,
      importRightMenu, importCondition, importForm } = docSearchStore;
    const { isFormInit } = importForm;
    const formParams = importForm.getFormParams();
    const { dummyIds } = formParams;
    const disabled = !dummyIds || importLoading;
    let com = null;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { form, comsWeaTableStore } = storeNow;
    const { selectedRowKeys } = comsWeaTableStore;

    isFormInit && importCondition.forEach((c) => {
      c.items.forEach((field) => {
        com = (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@bnm43m@${field.label}`}
          label={`${field.label}`}
          labelCol={{ span: field.labelcol }}
          wrapperCol={{ span: field.fieldcol }}
        >
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@uayw5c@${field.label}`} fieldConfig={field} form={importForm} formParams={formParams} />
        </WeaFormItem>);
      });
    });
    const onOk = () => {
      const params = importType === 'all' ? form.getFormParams() : {};
      docSearchStore.importDummy({
        importType,
        dummyIds,
        selectIds: `${selectedRowKeys}`,
        ...params,
      });
    };
    const onCancel = () => {
      docSearchStore.setState({ showImportDummy: false });
      importForm.reset();
    };
    const moreBtn = {
          datas: [{
            key: '1',
            disabled,
            icon: <i className="icon-coms-Preservation" />,
            content: getLabel(30986, '保存'),
            onClick: onOk,
          }],
          collectParams: {
            favname: getLabel(132039, '查阅文档'),
            favouritetype: 2,
            objid: 0,
            importantlevel: 1,
            link: 'wui/index.html#/main/document/search',
          },
        }
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@8yjem1`}
        className="wea-doc-dummy-modal"
        title={importCondition.length > 0 ? importCondition[0].title : ''}
        style={{ width: 500, height: 100 }}
        maskClosable={false}
        icon="icon-coms-doc"
        iconBgcolor="#df583a"
        visible={showImportDummy}
        onCancel={onCancel}
        buttons={
          [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@aq3f33@$dialogSave2`} type="primary"
              disabled={disabled}
              onClick={onOk}
            >{getLabel(30986, '保存')}</Button>),
          ]
        }
        moreBtn={moreBtn}
      >
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@bgb3ja`}
          datas={moreBtn.datas}
          collectParams={this.state.dropMenuProps.collectParams}
        >
          <div style={{ padding: 30 }}>
            <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@z3dzqo`} spinning={importLoading} >
              {com}
            </Spin>
          </div>
        </WeaRightMenu>
      </WeaDialog>
    );
  }
  getBreadcrumb=()=> {
    const { docSearchStore, routing } = this.props;
    const { prePath, prePathName } = docSearchStore;
    const arr = [];
    prePath && prePathName && arr.push({
      name: prePathName,
      onClick: () => {
        routing.push({ pathname: prePath, state: {} });
        docSearchStore.setState({ prePath: '', prePathName: '' });
      },
    });
    arr.push({
      name: getLabel(132039, '查阅文档'),
      onClick: () => { },
    });
    return arr;
  }

  thumbnailsOnChange = (ids) => {
    const { docSearchStore } = this.props;
    docSearchStore.setState({ checkedKeys: ids })
  }
  onTabChange = (val) => {
    const { docSearchStore, location } = this.props;
    const { query = {}, state = {} } = location;
    const { tabInfo, defaultTreeNode } = docSearchStore;
    const { viewcondition, getMost, secid, showSearchAd, showThumbnails, canCreate, leftTree } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { loading, comsWeaTableStore, form } = storeNow;
    const loadingNow = loading || comsWeaTableStore.loading;
    const modalCancel = () => {
      docSearchStore.setState({ mvisible: false });
    };
    const v = Number(val);
    const index = v > 2 ? 2 : v;
    docSearchStore.setState({
      viewcondition: v,
      selectedTreeKeys: [],
      showThumbnails: false,
      checkedKeys: [],
      treeDropMenuKey: defaultTreeNode,
    });
    form.reset();
    let groupid = '';
    tabInfo.forEach((tab) => {
      if (tab.viewcondition === v) groupid = tab.groupid;
    });

    this.props[store[index]]
      .getRightMenu('Search', { viewcondition: index })
      .getConditionInfo('Search', { viewcondition: v, groupid }, (result) => {
        this.props[store[index]].doSearch('Search', { ...query, ...result, viewcondition: v, groupid, secid });
      });
    // this.props[store[index]].treeDatas.length === 0 &&

    if (leftTree.showLeft) {
      this.props[store[index]]
        .getTreeDatas('Search', { ...query, viewcondition: index, secid, isFav: defaultTreeNode })
        .getTreeNums('Search', { ...query, viewcondition: index, secid, isFav: defaultTreeNode });
    } else {
      leftTree.hasLoad = false;
    }
    comsWeaTableStore.setSelectedRowKeys([]);
  }
  onTabSearch = () => {
    const { docSearchStore, location } = this.props;
    const { query = {} } = location;
    const { viewcondition, getMost, secid } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { form } = storeNow;
    storeNow.doSearch('Search', { ...query, viewcondition, getMost, secid, ...form.getFormParams() });
    docSearchStore.setState({ checkedKeys: [] });
  }
  setShowSearchAd = (bool) => {
    const { docSearchStore } = this.props;
    docSearchStore.setState({ showSearchAd: bool });
  }
  hideSearchAd = () => {
    const { docSearchStore } = this.props;
    docSearchStore.setState({ showSearchAd: false })
  }
  onSearchChange = (value) => {
    const { viewcondition } = this.props.docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { form } = storeNow;
    form.updateFields({ [this.quickSearchPara]: { value } })
  }
  searchsBaseValue = () => {
    const { docSearchStore } = this.props;
    const { viewcondition } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { form } = storeNow;
    return form.getFormParams()[this.quickSearchPara] || ''
  }

  onCollapse=()=> {
    const { docSearchStore } = this.props;
    const { query = {}, state = {} } = location;
    const { viewcondition, leftTree } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    docSearchStore.doCollapse();
    if (leftTree.hasLoad) {
      return true;
    }
    storeNow.getTreeDatas('Search', { ...query, viewcondition, isFav: docSearchStore.defaultTreeNode });
    // .getTreeNums('Search', {  ...query,viewcondition });
  }
  render() {
    const { docSearchStore, location } = this.props;
    const { query = {}, state = {} } = location;
    const { tabInfo, defaultTreeNode } = docSearchStore;
    const { viewcondition, getMost, secid, showSearchAd, showThumbnails, canCreate, leftTree } = docSearchStore;
    const storeNow = this.props[store[viewcondition > 2 ? 2 : viewcondition]];
    const { loading, comsWeaTableStore, form } = storeNow;
    const loadingNow = loading || comsWeaTableStore.loading;
    const modalCancel = () => {
      docSearchStore.setState({ mvisible: false });
    };
    return (
      <div className="wea-doc-search">
        <WeaIntro ecId={`${this && this.props && this.props.ecId || ''}_WeaIntro@hq6si6`} />
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@r7oekx`}
          datas={this.getRightMenu()}
          collectParams={this.state.dropMenuProps.collectParams}
        >
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@afol53`}
            breadcrumb={this.getBreadcrumb()}
            loading={loadingNow}
            icon={<i className="icon-coms-doc" />}
            iconBgcolor="#df583a"
            buttons={this.getRightMenu(true)}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            dropMenuProps={this.state.dropMenuProps}
          >

            <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@65cq36`}
              isNew={true}
              leftCom={this.getTree()}
              showLeft={leftTree.showLeft}
              onCollapse={this.onCollapse}
            >
              <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@8xbbi7`}
                type="editable-inline"
                buttonsAd={this.getTabButtonsAd()}
                searchType={this.state.searchType}
                searchsBaseValue={this.searchsBaseValue()}
                searchsAd={this.getSearchs()}
                showSearchAd={showSearchAd}
                setShowSearchAd={this.setShowSearchAd}
                hideSearchAd={this.hideSearchAd}
                keyParam="viewcondition"
                datas={toJS(tabInfo)}
                selectedKey={viewcondition}
                className="wea-doc-search-tab"
                onChange={this.onTabChange}
                onSearch={this.onTabSearch}
                onSearchChange={this.onSearchChange}
                onEdit={this.onTabEdit}
              />
              <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@wv0js0`}
                comsWeaTableStore={comsWeaTableStore}
                showThumbnails={showThumbnails}
                hasOrder={true}
                needScroll={true}
                thumbnailsOnChange={this.thumbnailsOnChange}
                onOperatesClick={this.onOperatesClick}
              />
            </WeaLeftRightLayout>
          </WeaTop>
        </WeaRightMenu>
        {this.getDocShare()}
        {this.getDocLog()}
        {this.getConditonSave()}
        {this.getImportDummy()}
        <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@65hnnt`} pathname="/document/search" secid="-1" docid="-1" />
      </div>
    );
  }
}

export default Search;
